<?php
declare(strict_types=1);

namespace app\salesman\model\order;

use app\common\model\Export;
use app\model\Agent;
use app\model\MobileOrder;
use think\Db;

class Mobile extends MobileOrder
{
    /**
     * 充值状态常量
     */
    const C_TAB_RECHARGE_ALL = 'all';  // 全部
    const C_TAB_RECHARGE_ING = 'ing';  // 正在充值
    const C_TAB_RECHARGE_FAIL = 'fail';  // 充值失败
    const C_TAB_RECHARGE_SUCCESS = 'success';  // 充值成功

    /**
     * 列表
     * @param $params
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function dataList($params) {
        $supplierStatusArr = [];
        $tabStatus = $params['tab_status'] ?? self::C_TAB_RECHARGE_ALL;
        switch ($tabStatus) {
            case self::C_TAB_RECHARGE_FAIL: // 充值失败
                $supplierStatusArr = self::$supplierStatusFailArr;
                break;
            case self::C_TAB_RECHARGE_SUCCESS:  // 充值成功
                $supplierStatusArr = self::C_SUPPLIER_STATUS_SUCCESS;
                break;
            case self::C_TAB_RECHARGE_ING:  // 正在充值
                $supplierStatusArr = [self::C_SUPPLIER_STATUS_NO_CREATE, self::C_SUPPLIER_STATUS_CREATE];
                break;
            default:
                break;
        }

        $keyword = $params['keyword'] ?? '';
        $orderType = $params['order_type'] ?? '';

        $query = MobileOrder::where([
            'salesman_id' => $params['salesman_id'],
            'status' => MobileOrder::C_STATUS_HAVE
        ]);
        // 充值状态
        $query->when($supplierStatusArr, function ($subQuery) use ($supplierStatusArr) {
                $subQuery->where(['supplier_status' => $supplierStatusArr]);
            })
            // 充值号/系统订单号
            ->when($keyword, function ($subQuery) use ($keyword) {
                $subQuery->where('mobile|sub_order_id', 'like', '%' . $keyword . '%');
            })
            // 充值类型
            ->when($orderType, function ($subQuery) use ($orderType) {
                $subQuery->where(['order_type' => $orderType]);
            });

        // 下单时间 => 创建时间
        $createStart = $params['create_start'] ?? '';
        $createEnd = $params['create_end'] ?? '';
        if ($createStart && $createEnd) {
            $createEnd =  $createEnd . ' 23:59:59';
            $query->whereBetweenTime('created_at', $createStart, $createEnd);
        }

        // 完成时间
        $finishStart = $params['finish_start'] ?? '';
        $finishEnd = $params['finish_end'] ?? '';
        if ($finishStart && $finishEnd) {
            $finishEnd =  $finishEnd . ' 23:59:59';
            $query->whereBetweenTime('finish_time', $finishStart, $finishEnd);
        }

        // 代理商查询
        $agentName = $params['agent_name'] ?? '';
        if ($agentName) {
            $agentIds = Agent::where('username|company_name', 'like', '%' . $agentName . '%')
                ->column('id');
            $agentIds = empty($agentIds) ? -1 : $agentIds;
            $query->where(['agent_id' => $agentIds]);
        }

        // 代理商字段预加载
        $query->with(['agent' => function ($agentQuery) {
            $agentQuery->field(['id', 'username', 'company_name']);
        }]);

        $query->field([
                'id', 'agent_id', 'sub_order_id', 'out_order_id', 'mobile', 'amount',
                'sale_price', 'order_type', 'status', 'official_sn', 'order_from',
                'supplier_status', 'created_at', 'finish_time',
            ])
            ->order('id desc');

        $isExport = $params['is_export'] ?? '';
        // 文本映射
        $appendArr = ['isp_type_text', 'order_type_text', 'spend'];
        if (!empty($isExport)) {
            $appendArr[] = 'supplier_status_text';
        }
        $query->append($appendArr);


        if (!empty($isExport)) {
            // 导出Excel表
            $data = $query->select()->toArray();
            return $this->downloadExcel($data);
        } else {
            $list = $query->paginate()->toArray();
            return success('操作成功', $list);
        }
    }

    /**
     * excel列表导出
     * @param $data
     */
    protected function downloadExcel($data) {
        $fieldArr = [
            '系统订单号' => 'sub_order_id',
            '接口订单号' => 'out_order_id',
            '代理商用户名' => 'agent_username',
            '代理商公司名称' => 'agent_company_name',
            '销售价' => 'sale_price',
            '充值号码' => 'mobile',
            '充值金额' =>  'amount',
            '运营商' => 'isp_type_text',
            '充值类型' =>  'order_type_text',
            '充值状态' => 'supplier_status_text',
            '下单时间' => 'created_at',
            '完成时间' => 'finish_time',
            '耗时' => 'spend',
        ];

        // 需要加\t 字段处理
        $fieldAddT = [
            'sub_order_id', 'out_order_id'
        ];

        // 单位 分转成元 字段处理
        $fieldPriceUnit = [
            'sale_price',
            'amount',
        ];

        // 数据和导出字段名一一对应
        $res = [];
        foreach ($data as $item) {
            $temp = [];
            foreach ($fieldArr as $name => $field) {
                $value = $item[$field] ?? '';
                if (in_array($field, $fieldAddT)) {
                    $value = $value ? $value . "\t" : '';
                } elseif (in_array($field, $fieldPriceUnit)) {
                    $value = $value ? fen2yuan($value) : '';
                } elseif ($field == 'agent_username') {
                    $value = $item['agent']['username'] ?? '';
                } elseif ($field == 'agent_company_name') {
                    $value = $item['agent']['company_name'] ?? '';
                }
                $temp[] = $value;
            }
            $res[] = $temp;
        }
        $export = new Export;
        $name = '话费订单';
        return $export->downloadExcel(array_keys($fieldArr), $res, $name);
    }


}